package cl.whyem.springoxm.test.app;

import cl.whyem.springoxm.test.pojo.Desarrollador;
import cl.whyem.springoxm.test.pojo.Empleado;
import cl.whyem.springoxm.test.pojo.Jefe;
import cl.whyem.springoxm.test.pojo.Root;
import cl.whyem.springoxm.test.util.MarshallerUtil;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Arrays;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;

public class Main {

    public static void main(String[] args) throws IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext("main-context.xml");
        Marshaller marshaller = (Marshaller) context.getBean("xstreamMarshallerBean");
        Jaxb2Marshaller marshallerJAX = (Jaxb2Marshaller) context.getBean("jaxb2Marshaller");

        Empleado empleado = new Empleado();
        empleado.setId(101);
        empleado.setName("Sonoo Jaiswal");
        empleado.setSalary(100000);
        empleado.setRut("1-9");

        Jefe jefe = new Jefe();
        jefe.setId(333);
        jefe.setName("The big boss");
        jefe.setSalary(10000000);
        jefe.setDepartment("IT department");

        String xml = MarshallerUtil.<Empleado>toXML(marshallerJAX, empleado);
        System.out.println("EMPLEADO -> \n" + xml);

        Empleado fromXML = MarshallerUtil.<Empleado>fromXML(marshallerJAX, xml);
        System.out.println("EMPLEADO (T) -> " + ToStringBuilder.reflectionToString(fromXML, ToStringStyle.SHORT_PREFIX_STYLE));

        final StringWriter out2 = new StringWriter();
        marshaller.marshal(jefe, new StreamResult(out2));
        System.out.println("JEFE -> " + out2.toString());

        Root root = new Root();
        root.setEmpleado(null);
        Desarrollador desarrollador = new Desarrollador();
        desarrollador.setSkills("java");
        root.setTrabajadores(Arrays.asList(empleado, desarrollador));
        String xml2 = MarshallerUtil.<Root>toXML(marshallerJAX, root);
        System.out.println("ROOT -> \n" + xml2);
        
        Root fromXML2 = MarshallerUtil.<Root>fromXML(marshallerJAX, xml2);
        System.out.println("ROOT (T) -> " + ToStringBuilder.reflectionToString(fromXML2, ToStringStyle.SHORT_PREFIX_STYLE));
    }
}
